########################################
##
## This modules implements some of the 
## commands necessary to deal with an
## IRC server.
##
##
def command( from_,
             command,
             to_,
             what ):
    if from_!="":
        return " ".join([":"+from_,command,to_,":"+what])
    else:
        if what!="":
            return " ".join([command,to_,":"+what])
        else:
            return command+" "+to


########################################
##
## Checks if the expression looks like a
## channel
##
## global channels begin with #
## server-local channels with &
## 
def channel_like( x ):
    return (x[2][0]=='#') or (x[2][0]=='&')

########################################
##
## returns true if the to field contains
## a non-channel expression
##
def private_like( x ):
    return not channel_like( x) 

########################################
##
## Extracts the part before !
##
def short_nick( long_nick ):
    return long_nick.split('!')[0]


########################################
##
## replies to the message as a directed
## private message, rather than on a channel
##
def reply_private(command, what):
    return [ '',command[1],short_nick(command[0]),':'+what ]

########################################
##
## Replies to the message as a NOTICE
##
def reply_notice(command, what):
    return [ '','NOTICE',short_nick(command[0]),':'+what ]


########################################
##
## returns a short nick (it gives DrMax
## from DrMax!n=Dr@mode..........ca
## since the from part from the IRC server
## cannot be used as a destination
##
def from_who( command ):
    return short_nick( command[0] )

########################################
##
## replies to a command using the right
## channel or nickname. This is used to
## reply to request in the same manner
## they were made; on-channel requests are
## replied on channel, private requests
## are replied to in private
##
## prepends : to messages
##
def reply( command, what ):

    # see if command as a 'to' field that
    # is nick-like or channel-like
    if channel_like( command ): # from, cmd, to, what
        return [ '',command[1],command[2], ':'+what ]
    else:
        # looks like a private message
        return reply_private( command, what  ) # ':' placed by reply_private

########################################
##
## parses the line in many field:
##
## from,
## command, (or numeric code)
## to,
## message
##
def parse( line ):

    parsed=['']*4
    temp=line.split(' ');

    # tries to parse
    if temp[0][0]==':':
    ## has a from
        parsed[0]=temp[0][1:]
        offset=1
    else:
        offset=0;

    parsed[1]=temp[0+offset] # command and to
    parsed[2]=temp[1+offset] # to

    if len(temp) > 2+offset:
#        if temp[2+offset][0]==":":
        parsed[3]=" ".join(temp[2+offset:])[1:] # skips :
#        else:
#            parsed[3]=" ".join(temp[2+offset:])
    else:
        parsed[3]='';

    return parsed
